import codemuseLogo from '@/assets/codemuseLogo.png';
import starIcon from '@/assets/star.png';
import { markdown } from '@/models/markdown';
import { createPageHtml } from '@/services/chat';
import { UserOutlined } from '@ant-design/icons';
import { Bubble } from '@ant-design/x';
import { Button, Image, theme } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

const fooAvatar: React.CSSProperties = {
  color: '#f56a00',
  backgroundColor: '#fde3cf',
  width: '40px',
  height: '40px',
};

const barAvatar: React.CSSProperties = {
  color: '#fff',
  backgroundColor: '#87d068',
};

declare type BubbleListProps = {
  messages: any;
  isExpanded: boolean;
  isModelLoading: boolean;
  conversationId: string;
  versions: any[];
  onClick: (content: string) => void;
  onPreview: () => void;
  setIsModelLoading: (
    val: boolean,
    isError: boolean,
    isSuccess: boolean,
  ) => void;
  onVersion: (params: any) => void;
  onVersionNum: (num: string) => void;
};

const BubbleList = (props: BubbleListProps) => {
  const {
    messages,
    isExpanded,
    isModelLoading,
    conversationId,
    versions,
    onClick,
    onPreview,
    setIsModelLoading,
    onVersion,
    onVersionNum,
  } = props;
  const [generationFinished, setGenerationFinished] = useState(false);
  const [generationFailed, setGenerationFailed] = useState(false);

  const { token } = theme.useToken();

  useEffect(() => {
    const generatingMessage = messages.findLast(
      (msg: any) => msg.message.text === '设计稿正在生成中，请稍等...',
    );
    console.log('generatingMessage=>>>>>', generatingMessage);
    if (generatingMessage && !generationFinished && !generationFailed) {
      const fetchPageHtml = async () => {
        try {
          const { code, data } = await createPageHtml({ conversationId });
          if (code === 200) {
            setGenerationFinished(true);
            if (data && data.pagePath) {
              const newversions = [...versions];
              newversions.push({
                version: data.version,
                name: data.version,
                desc: `${data.version}版本`,
                url: data.pagePath,
              });
              onVersion(newversions);
              onVersionNum(data.version);
            }
          } else {
            setGenerationFailed(true);
          }
        } catch (error) {
          console.error('Error fetching page HTML:', error);
          setGenerationFailed(true);
        }
      };

      fetchPageHtml();
    }
  }, [messages, generationFinished, generationFailed, conversationId]);

  const handleEditClick = (content: string) => {
    setGenerationFinished(false);
    setGenerationFailed(false);
    onClick(content);
  };

  const handleGoToPreview = () => {
    onPreview();
  };

  useEffect(() => {
    if (generationFailed || generationFinished) {
      setIsModelLoading(false, generationFailed, generationFinished);
    }
  }, [generationFailed, generationFinished]);

  const renderMarkdown: any = (content: any, role: string, index: number) => {
    const lastValidMessageIndex = messages
      .map(({ message }: any) =>
        typeof message === 'string'
          ? message.includes('生成代码')
          : message.text.includes('生成代码'),
      )
      .lastIndexOf(true);

    return (
      <div>
        <div dangerouslySetInnerHTML={{ __html: markdown(content) }} />
        {content.includes('生成代码') &&
          role !== 'user' &&
          index === lastValidMessageIndex && (
            <div className={styles.editButton}>
              <Button
                type="primary"
                onClick={() => handleEditClick(content)}
                icon={
                  <Image
                    src={starIcon}
                    width={25}
                    height={25}
                    preview={false}
                  />
                }
                disabled={isModelLoading}
              >
                去生成demo
              </Button>
            </div>
          )}
      </div>
    );
  };

  return (
    <div className={styles.bubbleList}>
      <Bubble.List
        items={[
          ...messages.map(({ message, id }: any, index: number): any => {
            const isModelResponse = !['user', 'file'].includes(message?.role);
            let content = typeof message === 'string' ? message : message.text;

            return {
              key: id,
              role: message?.role === 'user' ? 'user' : 'ai',
              content,
              placement: message?.role === 'user' ? 'end' : 'start',
              loading: message === '好的',
              avatar:
                message.role === 'user'
                  ? {
                      icon: <UserOutlined />,
                      style: fooAvatar,
                    }
                  : {
                      src: codemuseLogo,
                      style: {
                        width: '40px',
                        height: '40px',
                      },
                    },
              footer: content === '设计稿生成失败' ? '' : message.footer,
              messageRender: (content: any) =>
                renderMarkdown(content, message?.role, index),
            };
          }),
        ]}
      />
    </div>
  );
};

export default BubbleList;
